package com.nnnu.orange.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nnnu.orange.constant.MessageConstants;
import com.nnnu.orange.exception.AdminException;
import com.nnnu.orange.pojo.dto.LoginDto;
import com.nnnu.orange.pojo.entity.Admin;
import com.nnnu.orange.mapper.AdminMapper;
import com.nnnu.orange.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zk
 * @since 2024-11-07
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {


    @Override
    public Admin login(@NotNull LoginDto loginDto) {
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<Admin>()
                .eq(Admin::getUsername, loginDto.getUsername());
        Admin admin = getOne(wrapper);
        //用户不存在
        if (admin == null) {
            throw new AdminException(MessageConstants.ADMIN_ERR);
        }
        String password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        //密码不正确
        if (!admin.getPassword().equals(password)) {
            throw new AdminException(MessageConstants.ADMIN_PASSWORD_ERR);
        }
        //账号被禁用
        if (!admin.getStatus().equals(MessageConstants.NORMAL)) {
            throw new AdminException(MessageConstants.ACCOUNT_LOCKED);
        }
        return admin;
    }
}
